import { createRouter, createWebHistory } from "vue-router";
import { ElMessage } from "element-plus"; // 替换alert的美观提示，无需新增页面
import { useUserStore } from "@/store";

// 所有已存在的组件统一用懒加载（优化初始加载，不新增页面）
const Login = () => import("@/page/Login.vue");
const Main = () => import("@/page/Main.vue");
const NewsTypeList = () => import("@/components/main/TypeNewsList.vue");
const CategoryList = () => import("@/components/main/CategoryList.vue");

const Product = () => import("@/components/main/ProductList.vue");

const routes = [
  {
    path: "/",
    redirect: "/login" // 根路径重定向到登录页
  },
  {
    path: "/login",
    name: "Login",
    component: Login,
    meta: {
      requiresAuth: false
    }
  },
  {
    path: "/main",
    name: "Main",
    component: Main,
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: "news-type",
        name: "NewsTypeList",
        component: NewsTypeList,
        meta: {
          title: "新闻分类管理"
        }
      },
      {
        path: "categoryList",
        name: "CategoryList",
        component: CategoryList,
        meta: {
          title: "商品分类管理"
        }
      },
      {
        path: "productList",
        name: "Product",
        component: Product,
        meta: {
          title: "商品管理"
        },
      }, {
        path: "productEdit/:id?",
        name: "ProductEdit",
        component: () => import("@/components/main/ProductEdit.vue"),
      }
    ]
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes,
  // 滚动行为：切换路由时回到顶部（优化体验，不新增页面）
  scrollBehavior() {
    return { top: 0 };
  }
});

// 路由守卫（仅针对已有页面做权限控制）
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();

  // 给已有页面设置标题（优化体验，不涉及新增页面）
  if (to.meta.title) {
    document.title = `${to.meta.title} - 科泰购管理系统`;
  } else {
    document.title = "科泰购管理系统";
  }

  // 登录权限控制（仅针对已有页面）
  if (to.meta.requiresAuth) {
    // 未登录时跳登录页，用ElMessage替代alert（更美观）
    if (!userStore.isLogin) {
      ElMessage.warning("请先登录后再访问！");
      next("/login");
    } else {
      next();
    }
  } else {
    // 已登录状态访问登录页，自动跳转到已有首页（新闻分类列表）
    if (to.path === "/login" && userStore.isLogin) {
      next("/main/news-type");
    } else {
      next();
    }
  }
});

export default router;